const mongoose=require("mongoose")
const request=require("request")

var Order=mongoose.model("order")
var Merchant=mongoose.model("merchant")
var Food=mongoose.model("food")

var Vorder=require("../models/order.view.model")

var config=require("../config/config.js")

exports.findCompOrdersByPage=function(req,res){
	if(parseInt(req.params.page) ==0){
		res.json(null)
	}else{
		Order.find({})
		.where("oStatus").equals(parseInt(req.params.oStatus))
		.skip((parseInt(req.params.page)-1)*4).limit(4)
		.exec(function(err,orders){
			if (!err) {
				res.json(orders);
			} else {
				res.json({error:"findCompOrdersByPage"})
			}
		})
	}
}

exports.updateOrderStatus=function(req,res){
	Order.findByIdAndUpdate(req.params.oId,{oStatus:req.body.oStatus},function(err,oldOrder){
		if (!err) {
			res.send("success")
		} else {
			res.json({error:"updateOrderStatus"})
		}
	})
	if(req.body.oStatus==4){
		Merchant.findByIdAndUpdate(req.body.mId,{mStatus:4},function(err,oldMerchant){
			if(err){
				console.log("updateMerchantStatus error")
			}
		})
	}
	Food.find({mId:req.body.mId},function(err,foods){
		for (var food in foods) {
			console.log(typeof food)
			foods[food].remove(function(err){
				if(err){
					console.log("delete foods error")
				}
			})
		}
	})
}

exports.findCompOrderStatus=function(req,res){
		Order.findOne({})
		.where("_id").equals(parseInt(req.params.oId))
		.select("oStatus")
		.exec(function(err,o){
			if (!err) {
				res.json(o.oStatus);
			} else {
				res.json({error:"findCompOrderStatus"})
			}
		})
}

exports.getOrderDetailById=function(req,res){
	request(config.wsOrderDetail+req.params.oId,function(err,response,body){
		// console.log("-----------------")
		// console.log(JSON.parse(body));
		// console.log("-----------------")
		var b=JSON.parse(body)
		b.foodList=b.foodlist;
		// var vo=new Vorder();
		// vo.oId=b.oId;
		// vo.cId=b.cId;
		// vo.mId=b.mId;
		// vo.foodInfo=b.foodInfo;
		// vo.oStatus=b.oStatus;
		// vo.startTime=b.startTime;
		// vo.confirmTime=b.confirmTime;
		// vo.finishTime=b.finishTime;
		// vo.oStark=b.oStark;
		// vo.complaint=b.complaint;
		// vo.foodList=b.foodlist;
		// res.json(vo)
		res.json(b)
	})
		
}
